import React, { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, message } from 'antd';
import { SerialContext } from '../context/SerialContext';
import './ServoInputIdComponent.css';
import { RouterUtils } from '../context/router';

const ServoInputIdComponent: React.FC = () => {
  const navigate = useNavigate();
  const ctx = useContext(SerialContext);
  const [form] = Form.useForm();

  if (!ctx) return null;
  const { serialState, servoModel, setServoModel } = ctx;

  const checkSerialState = () => {
    if (!serialState.isSerialOpen) throw new Error('请先连接串口');
    if (serialState.isSerialSearch) throw new Error('请先停止搜索');
    if (serialState.isSerialUpgrade) throw new Error('请先停止升级！');
  };

  const validateAndNavigate = async () => {
    try {
      const { servoId } = await form.validateFields();
      const id = Number(servoId);
      if (!Number.isInteger(id) || id < 0)
        throw new Error('请输入有效的正整数ID');
      // todo
      // checkSerialState();
      setServoModel({ ...servoModel, servo_id: id });
      RouterUtils.toServo(id);
    } catch (err: any) {
      message.error(err.message || '请正确填写舵机ID后再进入详情');
    }
  };

  return (
    <div className="home-id-input">
      <Form form={form} layout="inline" className="home-id-form" onFinish={validateAndNavigate}>
        <Form.Item
          label="舵机 ID"
          name="servoId"
          rules={[
            { required: true, message: '请输入舵机ID' },
            {
              validator: (_, value) =>
                !value ||
                (Number.isInteger(Number(value)) && Number(value) >= 0)
                  ? Promise.resolve()
                  : Promise.reject('请输入有效的正整数ID'),
            },
          ]}
        >
          <Input
            placeholder="请输入舵机ID（整数）"
            allowClear
            className="home-id-inputbox"
          />
        </Form.Item>
      </Form>
      <Button
        type="primary"
        className="home-id-btn"
        onClick={validateAndNavigate}
      >
        进入详情
      </Button>
    </div>
  );
};

export default ServoInputIdComponent;
